AddCSLuaFile("cl_init.lua")
AddCSLuaFile("shared.lua")

include("shared.lua")

function ENT:Initialize()
	self:SetModel("models/weapons/w_missile_closed.mdl")
	self:PhysicsInitSphere(4 * SCALE)
	self:SetMoveType(MOVETYPE_VPHYSICS)
	self:SetSolid(SOLID_VPHYSICS)
	local phys = self:GetPhysicsObject()
	if phys:IsValid() then
		phys:EnableDrag(false)
		phys:EnableGravity(false)
		phys:Wake()
	end

	self.DeathTime = CurTime() + 30
end

function ENT:Think()
	local ct = CurTime()

	self:GetPhysicsObject():ApplyForceCenter(FrameTime() * SCALE * 1000 * self.Heading)

	if self.DeathTime < ct then
		self:Remove()
	elseif 0 < self:WaterLevel() then
		self:Explode()
	end

	self:NextThink(ct)
	return true
end

function ENT:PhysicsCollide(data, physobj)
	self:Explode(data.HitPos, data.HitNormal)
end

ROCKETPOWER = 1000000
function ENT:Explode(hitpos, hitnormal)
	if self.Exploded then return end
	self.Exploded = true
	self.DeathTime = -10

	local owner = self.Owner
	if not owner:IsValid() then owner = self end
	hitpos = hitpos or self:GetPos()

	local effectdata = EffectData()
		effectdata:SetOrigin(hitpos)
		effectdata:SetNormal(hitnormal or Vector(0,0,1))
	util.Effect("rocketexplosion", effectdata)

	local radius = 350 * SCALE
	for _, ent in pairs(ents.FindInSphere(hitpos, radius)) do
		local phys = ent:GetPhysicsObject()
		if phys:IsValid() and phys:IsMoveable() and ent:GetMoveType() == MOVETYPE_VPHYSICS then
			local nearest = ent:NearestPoint(hitpos)
			phys:ApplyForceOffset(SCALE * ROCKETPOWER * ((radius - nearest:Distance(hitpos)) / radius) * (nearest - hitpos):Normalize(), nearest)
		end
	end

	util.BlastDamage(self, owner, hitpos, radius, 75)
end

function ENT:UpdateTransmitState()
	return TRANSMIT_PVS
end
